package com.jf.cloud.service.sysmanager.remote.api;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.util.HttpServletUtil;
import com.jf.cloud.service.sysmanager.dao.ISmsService;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 短信相关 统一处理
 */
@Controller
@RequestMapping("/sms")
public class SmsController extends BaseController {
	
	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(SmsController.class);
	
	/**
	 * 短信相关服务
	 */
	@Resource
	private ISmsService smsService;
	
	/**
	 * 
	 * 发送短信
	 * 
	 * @author 姚龙   创建时间：2017-05-02 13:56:50
	 */
	@ResponseBody
	@RequestMapping("/sendCaptchaSms")
	public Result<String> sendCaptchaSms(String userPhone, String modelType, String captcha, HttpServletRequest request) {
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("检查状态失败");
		String rs = "";
		try {
//			captcha = "123";
//			if (StringUtil.isEmpty(captcha)) {
//				return "-2"; // 图片验证码不能为空
//			}
//			String realCaptcha = (String) request.getSession().getAttribute("captcha_" + modelType);
//			if (StringUtil.isEmpty(realCaptcha) || !captcha.equals(realCaptcha)) {
//				return "-3"; // 图片验证码错误
//			}
			
			// 检查IP或手机号限制
			result = smsService.check(HttpServletUtil.getIp(request), userPhone, modelType);
			if (0 != result.getCode()) {
				return result;
			}
			
			rs = smsService.sendCaptchaSms(userPhone, modelType);
			if (rs == null || "null".equals(rs)) {
				result.setCode(-103);
				result.setMessage("发送短信失败！");
			} else {
				result.setCode(0);
				result.setData(rs);
				result.setMessage("发送短信成功！");
			}
		} catch (Exception e) {
			log.error("发送 手机验证码出错了！用户手机【" + userPhone + "】，用户IP:" + getLoginIp(request), e);
		}
		return result;
	}

	/**
	 * 
	 * 验证手机验证码是否正确
	 * 
	 * @author 姚龙   创建时间：2017-05-12 14:12:47
	 */
	@ResponseBody
	@RequestMapping("/checkSMS")
	public String checkSMS(Long userId, String userPhone, String modelType, String phoneCode) {
		String rs = "-1";
		try {
			rs = smsService.checkSMS(userId, userPhone, modelType, phoneCode);
		} catch (Exception e) {
			log.error("校验 手机验证码出错了！", e);
		}
		return rs;
	}
	
}
